from datetime import datetime, timedelta, time
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger

from app.celery_task.models.celery_task import CeleryTask

class CeleryTaskHandler():
    """  CeleryTask Handler
    """
    def __init__(self):
        pass


    def get_celery_task_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        异步任务单表, 根据表字段-模糊查询, 获取celery异步任务信息
        """
        try:
            field_info = {field: value}
            order_info = {"start_at": "desc"}
            result = CeleryTask.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.error(f"get celery task search, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get celery task search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_celery_task_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        try:
            result = CeleryTask.filter_by_field_match(db, page, per_page,{field: value})
            if not result:
                logger.warning(f"get celery task match failed, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get celery task match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def add_celery_task(self, db: Session, data: dict):
        try:
            celery_task_object = CeleryTask.get_object_by_tag(db, data["tag_key"], data["tag_value"])
            if celery_task_object:
                # 如果存在， 则异常返回
                logger.error(f"add celery task failed, {data['tag_key']}:{data['tag_value']} was exist")
                return False

            # 添加异步任务信息
            result = CeleryTask.add(db, data)
            if not result:
                logger.error(f"add celery task to database failed")
                return False
        except Exception as e:
            message = f"add celery task error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def update_celery_task(self, db: Session, data: dict):
        try:
            celery_task_object = CeleryTask.get_object_by_uuid(db, data['uuid'])
            if not celery_task_object:
                # 如果不存在， 则异常返回
                logger.error(f"update celery task failed, uuid:{data['uuid']} not exist")
                return False

            # 更新异步任务信息
            result = CeleryTask.update(db, data)
            if not result:
                logger.error(f"update celery task to database failed")
                return False
        except Exception as e:
            message = f"update celery task error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def delete_celery_task(self, db: Session, data: dict):
        """
        异步任务单表, 删除异步任务
        """
        try:
            celery_task_object = CeleryTask.get_object_by_uuid(db, data['uuid'])
            if not celery_task_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete celery task failed, uuid:{data['uuid']} not exist")
                return False

            # 删除异步任务信息
            CeleryTask.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete celery task error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def get_celery_state(self, db: Session):
        """
        获取celery的工作状态
        """
        try:
            # 
            celery_watchdog = CeleryTask.get_object_by_name(db, "watch_dog")
            if not celery_watchdog:
                logger.error(f"celery watchdog not exist")
                return False

            celery_watchdog_info = celery_watchdog.object_to_dict(db)
            now_timestamp = datetime.now().timestamp()
            update_timestamp = datetime.timestamp(celery_watchdog_info["update_at"] + timedelta(minutes=15))
            if update_timestamp < now_timestamp:
                logger.error(f"celery watchdog no running last 15 minutes")
                return False
        except Exception as e:
            logger.exception(f"set celery state error => {e}")
            return False

        return True

